package com.atguigu.gulimall.member.interceptor;

import com.atguigu.common.constant.AuthServerConstant;
import com.atguigu.common.vo.MemberResp;
import com.atguigu.gulimall.member.utils.LoginUserUtils;
import org.apache.ibatis.plugin.Interceptor;
import org.springframework.util.AntPathMatcher;
import org.springframework.util.ObjectUtils;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * @Description
 * @Author lhj
 * @Date 2024/5/25 14:45
 */
public class MemberInterceptor implements HandlerInterceptor {
    
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String uri = request.getRequestURI();
        AntPathMatcher pathMatcher = new AntPathMatcher();
        boolean passed = pathMatcher.match("/member/member/**", uri);
        boolean match = pathMatcher.match("/member/memberreceiveaddress/**", uri);
        if (match || passed) {
            return true;
        }
        HttpSession session = request.getSession();
        //获取Redis缓存信息
        Object loginInfo = session.getAttribute(AuthServerConstant.LOGIN_USER);
        //没有登陆重定向到登录页面
        if (ObjectUtils.isEmpty(loginInfo)) {
            response.sendRedirect("http://auth.gulimall.com/login.html");
            return false;
        }
        //登陆成功后将用户信息保存到ThreadLocal 以供当前线程在其他任何地方获取使用
        MemberResp memberResp = (MemberResp) loginInfo;
        LoginUserUtils.set(memberResp);
        return true;
    }
}
